import Vue from 'vue';
import Vuex from 'vuex';
import app from './modules/app';
import request from '@/utils/axios';
import { Encrypt, Decrypt} from '@/utils/secret';

Vue.use(Vuex);

export default new Vuex.Store({
  modules: {
      // app,
  },
  state: {
    fingerprint: '',
    IMEI: '',
    deviceID: '',
    activeCode: '',
    agreeAgreement: false,
    agreementVisible: false,
    activationVisible: false,
    isEffective: false,
    expiresTime: '',
    activeState: 1,
  },
  getters: {},
  mutations: {
    SET_TOTLE_DATA: (state, params) => {
      Object.keys(params).forEach(key => state[key] = params[key]);
    },
  },
  actions: {
    getDeviceInfo: async ({ commit, dispatch }) => {
      const { fingerprint, IMEI, activeCode, deviceID } = await AutoWeb.autoPromise('getDeviceInfo');
      // const fingerprint = 'XiaomiO;jb.gh/vangogh:11/RKQ1.200826.002/V12.5.7.0.RJVCNXM:user/release-keys';
      // const IMEI = '7a24f908254d4ef6';
      // const activeCode = 'NBdrWlDYDG31';
      // const deviceID = '90f44528ed';
      commit('SET_TOTLE_DATA', {
        fingerprint,
        IMEI,
        activeCode,
        deviceID,
      });
      if (!activeCode) {
        commit('SET_TOTLE_DATA', {activationVisible: true});
        return;
      }
      setInterval(() => {
        dispatch('getActiveState');
      }, 30000);
    },
    getActiveState: async ({ state, commit }) => {
      const code = Encrypt(JSON.stringify({
        deviceCode: state.IMEI,
        activeCode: state.activeCode,
        deviceID: state.deviceID,
      }));
      const { data } = await request.post('/app/activate/state', { code });
      const activeInfo = JSON.parse(Decrypt(data));
      const { isEffective, expiresTime, activeState } = activeInfo || {};
      commit('SET_TOTLE_DATA', {
        isEffective,
        expiresTime,
        activeState,
      });
    },
    initCheck: ({ state, commit }) => {
      // 是否激活
      if (!state.isEffective) {
        commit("SET_TOTLE_DATA", { activationVisible: true });
        return false;
      }
      // 是否同意协议
      if (!state.agreeAgreement) {
        commit("SET_TOTLE_DATA", { agreementVisible: true });
        return false;
      }
      return true;
    }
  },
});
